package lib.core.controller
{
	import lib.config.ModuleConfig;
	
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	public class RequestUrlInfo
	{
		public static const DEFAULT_ACTION:String = "Index";
		public static const NOT_FOUND:String = "NotFound";
		
		private var _module:String;
		private var _actualModule:String;
		private var _rawModule:String;
		private var _action:String;
		private var _requestedAction:String;
		private var _parameters:ArrayCollection = new ArrayCollection();
		private var _rawUrl:String;
		private var _rawAction:String;
		
		public function get action():String
		{
			return this._action;
		}
		public function get requestedAction():String
		{
			return this._requestedAction;
		}
		public function get rawAction():String
		{
			return this._rawAction;
		}
		public function get module():String
		{
			return this._module;
		}
		public function get rawModule():String
		{
			return this._rawModule;
		}
		public function get rawUrl():String
		{
			return this._rawUrl;
		}
		public function get actualModule():String
		{
			return this._actualModule;
		}
		public function get parameters():ArrayCollection
		{
			return this._parameters;
		}
		
		public function get isValid():Boolean
		{
			return this.action != NOT_FOUND;
		}
		
		public function RequestUrlInfo(url:String)
		{
			this._rawUrl = url;
			if (url.length > 0)
			{
				if (url.search("/") > -1)
				{
					_module = StringUtil.trim(url.substr(0, url.indexOf("/")));
					
					// setup action name
					url = url.substr(url.indexOf("/")+1);
					if (url.search("/") > -1)
					{
						_action = url.substr(0, url.indexOf("/"));
						// setup parameters
						url = url.substr(url.indexOf("/")+1);
						this._parameters = new ArrayCollection(url.split("/"));
					}
					else 
					{
						_action = url;	
					}
					if (!isNaN(Number(_action)))
					{
						_parameters.addItemAt(_action, 0);
						_action = DEFAULT_ACTION;
					} else {
						_rawAction = _action;
						_action = RequestUrlInfo.ucFirst(_action);
					}
				} else {
					_module = url;
					_action = DEFAULT_ACTION;
				}
				_requestedAction = _action;
				_rawModule = _module;
				_module = RequestUrlInfo.ucFirst(_module);
				
				if (!ModuleConfig.isModuleEnabled(_module))
				{
					_actualModule = ModuleConfig.DEFAULT_MODULE;
					_action = NOT_FOUND;
				} else {
					_actualModule = _module;
				}
			} else {
				_module = ModuleConfig.DEFAULT_MODULE;
				_actualModule = _module;
				_action = DEFAULT_ACTION;
				_requestedAction = _action;
			}		
		}
		
		public function setActionDefault():void
		{
			this._action = DEFAULT_ACTION;
		}
		
		public static function ucFirst(value:String):String
		{
			value = value.toLowerCase();
			var first:String = value.substr(0, 1);
			var rest:String = value.substr(1);
			return first.toUpperCase()+rest;	
		}
	}	
}